package com.blkj.iam.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.blkj.iam.common.constant.CommonConstant;

import java.util.Date;

/**
 * @description: JwtUtil工具类
 * @author: Ethan
 * @create: 2025-04-24
 **/
public class JwtUtil {

    /***
     * Token 签名
     * @param username
     * @param password
     * @return: java.lang.String
     */
    public static String sign(String username, String password) {
        Date date = new Date(System.currentTimeMillis() + CommonConstant.EXPIRE_TIME_7_DAYS);
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 附带username信息
        return JWT.create().withClaim("username", username).withClaim("isPc", true).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
